package com.sweet.file;

import com.sweet.enums.Charset;
import com.sweet.lang.StringUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 文件下载
 *
 * @author limi
 * @version 1.2.0 2016-06-21 14:20
 */
@Slf4j
public final class FileDownload {
    /**
     * 文件下载
     *
     * @param request
     * @param response
     * @param absoluteFileName 文件绝对路径
     * @param isDelete         是否删除已下载文件
     * @return
     */
    public static String download(HttpServletRequest request, HttpServletResponse response, String absoluteFileName, boolean isDelete) {
        long start = System.currentTimeMillis();

        try {
            // 定义下载文件
            File downFile = new File(absoluteFileName);
            if (downFile == null || !downFile.exists() || !downFile.isFile()) {
                log.error("下载文件失败，文件不存在或非文件！");
                return null;
            }

            // 文件名转码，防止乱码
            String fileName = downFile.getName();
            String userAgent = request.getHeader("User-Agent");
            if (StringUtil.isNotBlank(userAgent) && userAgent.toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, Charset.UTF8.getCharset());
            } else {
                fileName = new String(fileName.getBytes(Charset.UTF8.getCharset()), "ISO8859-1");
            }

            // 设置响应头
            response.setCharacterEncoding(Charset.UTF8.getCharset());
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

            // 定义输入流
            InputStream is = new FileInputStream(downFile);

            // 定义输出流
            OutputStream os = response.getOutputStream();

            // 以写字节的方式写文件
            int b = 0;
            while ((b = is.read()) != -1) {
                os.write(b);
            }

            // byte[] d = new byte[2048];
            // while ((b = is.read(d))!=-1) {
            // os.write(d, 0, b);
            // }

            os.flush();
            os.close();
            is.close();

            log.info("文件下载完毕,耗时[" + (System.currentTimeMillis() - start) + "]毫秒......");

            // 删除源文件
            if (isDelete) {
                downFile.delete();
                log.info("文件下载完毕,耗时[" + (System.currentTimeMillis() - start) + "]毫秒.已删除源文件.....");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("下载文件异常，文件不存在!", e);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("下载文件异常！", e);
        }

        // 返回值要注意，要不然就出现下面这句错误！
        // java+getOutputStream() has already been called for this response
        return null;
    }
}